<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-3-18
 * Time: 下午7:25
 * 厂商运营商管理
 */
namespace Admin\Controller;
use Mcit\Page;
class FacController extends BaseController {

    //首页
    public function index(){

        //控制切换厂商运营商 1--运营商
        if($_GET['tab'] == 1){
            $map['type'] = array("eq",3);
        }else{
            $map['type'] = array("eq",2);
        }
        //区分管理员与子管理员
        if(!empty($_GET['parent'])){
            $map['pid'] = array("eq",I('parent'));
        }else{
            $map['pid'] = array("eq",0);
        }
        //用于运营商页【运营商名称】查询
        if(!empty($_GET['fac_name'])){
            $map['fac_name'] = array('like','%'.I('fac_name').'%');
        }
        //系统管理员账户
        $map['fac_login_name'] = array("neq",'root');
        //用于厂商页【厂商编号】查询
        if(!empty($_GET['fac_login_name'])){
            $map['fac_login_name'] = array('like','%'.I('fac_login_name').'%');
        }
        //分页
        $count = M("fac")->where($map)->order("id")->count();
        vendor('Mcit.Sys.Page');
        $Page = new Page($count, 20);
        $pageView = $Page->show();
        $this->assign('pageView', $pageView); //发送分页
        $nowPage = isset($_GET['page']) ? $_GET['page'] : 1;
        $this->fac = M("fac")->where($map)->page($nowPage . ',' . $Page->listRows)->order("id")->select();
//        echo M()->getLastSql();
        //分页结束
        $this->display();
    }
    //详情页
    public function detail(){
        if(IS_GET){
            $this->fac = M("fac")->where("id='".I('id')."'")->find();
        }
        $this->display();
    }
    //新增账户
    public  function addFac(){

        if(IS_POST){
            $type = I("type");
            //上传
            $config = array(
                'maxSize'       =>  3145728, //上传的文件大小限制 (0-不做限制)
                'exts'          =>  array('jpg', 'gif', 'png', 'jpeg'), //允许上传的文件后缀
                'autoSub'       =>  true, //自动子目录保存文件
                'subName'       =>  array('date', 'Ymd'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
                'rootPath'      =>     './Public/', //保存根路径
                'savePath'      =>  './data/upload/face/', //保存路径
                'saveName'      =>  array('uniqid', ''), //上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
            );
            $upload = new \Think\Upload($config); // 实例化上传类
            $info = $upload->uploadOne($_FILES['logo']);
            if (!$info) { // 上传错误提示错误信息
                //$this->error($upload->getError());
            } else { // 上传成功 获取上传文件信息
                $logo     = $info[savepath].$info[savename];
            }
            $configs = array(
                'maxSize'       =>  3145728, //上传的文件大小限制 (0-不做限制)
                'exts'          =>  array('jpg', 'gif', 'png', 'jpeg'), //允许上传的文件后缀
                'autoSub'       =>  true, //自动子目录保存文件
                'subName'       =>  array('date', 'YmdHis'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
                'rootPath'      =>     './Public/', //保存根路径
                'savePath'      =>  './data/upload/face/', //保存路径
                'saveName'      =>  array('uniqid', ''), //上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
            );
            $uploads = new \Think\Upload($configs); // 实例化上传类
            $infos = $uploads->uploadOne($_FILES['portrait']);
            if (!$infos) { // 上传错误提示错误信息
                //$this->error($uploads->getError());
            } else { // 上传成功 获取上传文件信息
                $portrait = $infos[savepath].$infos[savename];
            }
            $time                  = date("Y-m-d H:i:s",time());
            $map['fac_login_name'] = I("fac_login_name");
            if(M('fac')->where($map)->find()){
                $return['state'] = 200;
                $return['msg']   = "此账号已经使用";
                echo json_encode($return);
                exit;
            }
            $data = $_POST;
            $data['logo']        = $logo;
            $data['portrait']    = $portrait;
            $data['create_time'] = $time;
            //type字段用于区分厂商与运营商：2--厂商  3--运营商
            if($type == 3){
                $data['fac_password'] = sha1(I('fac_password'));
                $data['role']         = 888;
            }elseif($type == 2){
                $data['role']         = 777;
            }
            $result = M('fac')->add($data);
            if($result){
                if($type == 2){
                    //添加默认类型【一级】
                    $sqldata['name']            = "未知";
                    $sqldata['manufacturer_id'] = $result;
                    $Result = M("device_type")->add($sqldata);
                    if($Result){
                        //添加默认类型【二级】
                        if(!M("device_type")->where("pid='".$Result."' and level = 2 ")->find()){
                            $data['level']           = 2;
                            $data['name']            = "未知";
                            $data['pid']             = $Result;
                            $data['manufacturer_id'] = $result;
                            M("device_type")->add($data);
                        }
                    }
                    $return['url']   = U('Fac/index');
                }elseif($type == 3){
                    $return['url']   = U('Fac/index',array('tab'=>1));
                }
                $return['state'] = 100;
                $return['msg']   = '添加成功';
            }else{
                $return['state'] = 200;
                $return['msg']   = '添加失败';
            }
            echo json_encode($return);
            exit;
        }
        $this->display();
    }
    //修改账户信息
    public function editFac(){
        if(IS_GET){
            $this->fac = M("fac")->where("id='".I('id')."'")->find();
        }
        if(IS_POST){
            $map['id'] = I("id");
            $data = $_POST;
            $result = M('fac')->where($map)->save($data);
            if($result){
                $return['state'] = 100;
                $return['msg']   = '修改成功';
                $return['url']   = U('Fac/index');
            }else{
                $return['state'] = 200;
                //$return['msg']   = M("fac")->getLastSql();
                $return['msg']   = '修改失败';
            }
            echo json_encode($return);
            exit;
        }
        $this->display();
    }

    //密码设置
    public function editFacPwd(){
        if(IS_POST){

            $map['id'] = I("id");
            $type      = I("type");
            $map['fac_login_name']  = I("fac_login_name");//账号
            $pwd1  = I("pwd1");//新密码
            $pwd2  = I("pwd2");//重复密码
            if($pwd1 == $pwd2){
                if($type == 3){
                    //运营商密码为加密
                    if(M('fac')->where("id='".$map['id']."' and fac_password='".$pwd2."'")->find()){
                        $return['state'] = 100;
                        $return['msg']   = "保存成功！";
                        $return['url']   = U('Fac/index',array('tab'=>1));
                        echo json_encode($return);
                        exit;
                    }else{
                        $data['fac_password'] = md5($pwd2);//加密
                        $result = M('fac')->where($map)->save($data);
                        if($result){
                            $return['state'] = 100;
                            $return['msg']   = '修改成功！';
                            $return['url']   = U('Fac/index',array('tab'=>1));
                        }else{
                            $return['state'] = 200;
                            $return['msg']   = '修改失败';
                        }
                    }
                }elseif($type == 2){
                    //厂商密码为明文
                    if(M('fac')->where("id='".$map['id']."' and fac_password='".$pwd2."'")->find()){
                        $return['state'] = 100;
                        $return['msg']   = "保存成功！";
                        $return['url']   = U('Fac/index');
                        echo json_encode($return);
                        exit;
                    }else{
                        $data['fac_password'] = $pwd2;//明文
                        $result = M('fac')->where($map)->save($data);
                        if($result){
                            $return['state'] = 100;
                            $return['msg']   = '修改成功！';
                            $return['url']   = U('Fac/index');
                        }else{
                            $return['state'] = 200;
                            $return['msg']   = '修改失败';
                        }
                    }
                }
            }else{
                $return['state'] = 200;
                $return['msg']   = '两次密码输入不一致，请重新输入！';
            }

            echo json_encode($return);
            exit;
        }
    }

    //删除账户信息及关联的所有类型
    public function delFac(){
        if(IS_AJAX){
            $id            = I("id");
            $type          = I("type");
            if($type == 2){
                $user          = M("fac")->where("id='".$id."'")->find();
                $logodirs      = strsToArrays($user['logo']);
                $logodir       = APP_ROOT_PATH."./Public/".$logodirs[1]."/".$logodirs[2]."/".$logodirs[3]."/".$logodirs[4];
                if(file_exists(APP_ROOT_PATH."./Public/".$user['logo'])){
                    unlink(APP_ROOT_PATH."./Public/".$user['logo']);
                }
                rmdir($logodir);
                $portraitsdirs = strsToArrays($user['portrait']);
                $portraitdir   = APP_ROOT_PATH."./Public/".$portraitsdirs[1]."/".$portraitsdirs[2]."/".$portraitsdirs[3]."/".$portraitsdirs[4];
                if(file_exists(APP_ROOT_PATH."./Public/".$user['portrait'])){
                    unlink(APP_ROOT_PATH."./Public/".$user['portrait']);
                }
                rmdir($portraitdir);
                M("device_type")->where("manufacturer_id='".$id."'")->delete();
                $result = M("fac")->where("id='".$id."'")->delete();
            }elseif($type == 3){
                $result = M("fac")->where("id='".$id."'")->delete();
            }
            if($result){
                $return['state'] = 100;
                $return['msg']   = '删除成功';
                if($type == 3){
                    $return['url']   = U('Fac/index',array('tab'=>1));
                }else{
                    $return['url']   = U('Fac/index');
                }
            }else{
                $return['state'] = 200;
                $return['msg']   = '删除失败';
            }
            echo json_encode($return);
            exit;
        }
    }
    //类型管理
    public function manageFac(){
        $data = D("Fac")->getManufacNews(I("id"));
        //P($data);
        $this->device = $data;
        $this->display();
    }

    //新增一级分类
    public function addCategory(){
        $sqldata['name']            = I("category");
        $sqldata['manufacturer_id'] = I("id");
        $sqldata['pid']             = I("id");
        $map['name']                = $sqldata['name'];
        $map['manufacturer_id']     = $sqldata['manufacturer_id'];
        if(M("device_type")->where($map)->find()){
            $return['state'] = 200;
            $return['msg']   = "您已添加了该分类";
            echo json_encode($return);
            exit;
        }

        $result = M("device_type")->add($sqldata);
        if($result){
            if(!M("device_type")->where("pid='".$result."' and level = 2")->find()){
                $data['level']           = 2;
                $data['name']            = "未知";
                $data['pid']             = $result;
                $data['manufacturer_id'] = $sqldata['manufacturer_id'];
                M("device_type")->add($data);
            }
            $return['name']  = $sqldata['category'];
            $return['id']    = $result;
            $return['url']   = U('Fac/manageFac',array('id'=>$sqldata['manufacturer_id'],'newid'=>$result));
            $return['state'] = 100;
            $return['msg']   = "添加成功";
        }else{
            $return['state'] = 200;
            $return['msg']   = "添加失败";
        }
        echo json_encode($return);
        exit;
    }

    //新增二级分类
    public function addCategory2(){
        $sqldata['name']            = I("category2");
        $sqldata['pid']             = I("category");
        $sqldata['level']           = 2;
        $sqldata['manufacturer_id'] = I("parent_id");

        $map['name']  = $sqldata['name'];
        $map['manufacturer_id'] = $sqldata['manufacturer_id'];
        if(M("device_type")->where($map)->find()){
            $return['state'] = 200;
            $return['msg']   = "您已添加了该分类";
            echo json_encode($return);
            exit;
        }

        $result = M("device_type")->add($sqldata);
        if($result){
            $return['name']  = $sqldata['name'];
            $return['id']    = $result;
            $return['pid']   = $sqldata['pid'];
            $return['state'] = 100;
            $return['msg']   = "添加成功";
        }else{
            $return['state'] = 200;
            $return['msg']   = "添加失败";
        }
        echo json_encode($return);
        exit;
    }

    //修改一级\二级类型
    public function editCategory(){
        $category = I("category");
        $sqldata['name']  = $category;
        $saveMap['id']    = I("id");
        $result = M("device_type")->where($saveMap)->save($sqldata);
        if($result){
            $return['category'] = $category;
            $return['state'] = 100;
            $return['msg']   = "保存成功";
        }else{
            $return['state'] = 200;
            $return['msg']   = "保存失败";
        }
        echo json_encode($return);
        exit;
    }

    //删除类型
    public function delCategory(){
        $id  = I("id");
        $pid = I("pid");
        if($pid == ""){
            $map['id'] = $id;
        }else{
            $map = "id='".$id."' OR pid='".$id."'";
        }
        $result = M("device_type")->where($map)->delete();
        if($result){
            $return['state'] = 100;
            $return['msg']   = "删除成功";
        }else{
            $return['state'] = 200;
            $return['msg']   = "删除失败";
            //$return['msg']   = M("device_type")->getLastSql();
        }
        echo json_encode($return);
        exit;
    }

    public function node(){
        if (IS_POST) {
            $sqlData = array();
            $sqlData ['module'] = 'Factory';
            $sqlData ['title']  = I('title');
            switch( I('level') ){
                case 'Action':
                    $sqlData ['name']   = $sqlData ['module'].'-'.I('Controller').'-'.I('Action');
                    $sqlData ['controller'] = I('Controller');
                    $sqlData ['action'] = I('Action');
                    $sqlData ['level']  = 3;
                    $sqlData ['code'] = md5( strtoupper($sqlData ['module'].$sqlData ['controller'].$sqlData ['action']) );
                    break;
                case 'Controller':
                    $sqlData ['name']   = $sqlData ['module'].'-'.I('Controller');
                    $sqlData ['controller'] = I('Controller');
                    $sqlData ['level']  = 2;
                    $sqlData ['code'] = md5( strtoupper($sqlData ['module'].$sqlData ['controller']) );
                    break;
            }

            $result = M('yy_node')->add($sqlData);
            if($result){
                $return['state'] = 100;
                $return['msg']   = "添加成功";
            }else{
                $return['state'] = 200;
                $return['msg']   = "添加失败";
            }
            echo json_encode($return);
            exit;
        }
        $this->display();
    }

    public function role(){
        $this->newid = $_GET['newid'];
        if(session('yy_role') == 666){
            $roleData = M('yy_role')->order('date desc')->select();
        }else{
            //厂商角色列表
            $roleData = M('yy_role')->where("id <> 666 and type=2")->order('date desc')->select();
            //运营商角色列表
            $roleData1 = M('yy_role')->where("id <> 666 and type=3")->order('date desc')->select();
        }
        //P($_SESSION);
        //P($roleData);
        $this->roleData = $roleData;
        $this->roleData1 = $roleData1;
        $this->display();
    }

    public function addRole(){
        $name = I('name');
        $map['name'] = $name;
        if(M('yy_role')->where($map)->find()){
            $return['state'] = 200;
            $return['msg']   = "角色名称已经使用";
            echo json_encode($return);
            exit;
        }
        $sqlData['name']     = $name;
        $sqlData['type']     = I('type');
        $sqlData['date']     = date('Y-m-d H:i:s');
        $result = M('yy_role')->where($map)->add($sqlData);
        if($result){
            $return['state'] = 100;
            $return['msg']   = "添加成功,请设置该角色权限";
            $return['url']   = U("Fac/role",array('newid'=>$result));
        }else{
            $return['state'] = 200;
            $return['msg']   = "设置失败";
        }
        echo json_encode($return);
        exit;
    }

    public function delRole(){
        $map['id'] = I('id');
        if($map['id'] == 666 || $map['id'] == 667){
            $return['state'] = 200;
            $return['msg']   = "无权操作，此为重要数据，不可删除";
        }else{
            $result = M('yy_role')->where($map)->delete();
            if($result){
                $return['state'] = 100;
                $return['msg']   = "删除角色成功";
            }else{
                $return['state'] = 200;
                $return['msg']   = "删除失败";
            }
        }
        echo json_encode($return);
        exit;
    }

    public function access(){
        $role = url_base64_decode ( I('role') );
        $map['id'] = $role;
        $roleInfo  = M('yy_role')->where($map)->find();
        $authInfo  = explode(",", $roleInfo['authcode']);
        $whereMap['level']  = array('neq',1);
        $result = M('yy_node')->where($whereMap)->order('level')->select();
        $nodeTree = array();
        foreach($result as $key=>$value){
            if($value['level']==2){
                $nodeTree[$value['controller']]['title']=$value['title'];
                $nodeTree[$value['controller']]['name'] =$value['name'];
            }else{
                if( in_array($value['code'],$authInfo) ){
                    $value['checked'] = 1;
                }else{
                    $value['checked'] = 0;
                }
                $nodeTree[$value['controller']]['detail'][]=$value;
            }
        }
        $this->roleInfo = $roleInfo;
        $this->nodeTree = $nodeTree;
        if(session('administrator')){
            $this->administrator = 1;
        }else{
            $this->administrator = 0;
        }
        $this->display();

    }

    public function setAccess(){
        $role = I('role');
        $map['id'] = $role;
        $sqlData['authstr']  = I('authstr');
        $sqlData['authcode'] = I('authcode');
        $sqlData['date']     = date('Y-m-d H:i:s');
        $result = M('yy_role')->where($map)->save($sqlData);
        if($result){
            $return['state'] = 100;
            $return['msg']   = "设置成功";
            $return['url']   = U("Fac/role");
        }else{
            $return['state'] = 200;
            $return['msg']   = "设置失败";
        }
        echo json_encode($return);
        exit;
    }
}